package action;

import org.apache.struts2.interceptor.validation.SkipValidation;

import service.UsersDAO;
import service.impl.UsersDAOImpl;

import com.opensymphony.xwork2.ModelDriven;

import entity.Users;

/**
 * 实现模型驱动 ModelDriven 用于接收表单数据。
 * @author thinkpad
 *
 */
public class UsersAction extends SuperAction implements ModelDriven<Users> {
	private static final long serialVersionUID = 1L;
	private Users user = new Users();
	
	public String login()
	{
		UsersDAO udao = new UsersDAOImpl();
		
		if (udao.usersLogin(user)) {
			//在session中保存登录成功的用户名
			session.setAttribute("loginUserName", user.getUsername());
			return "login_success";
		}
		else
		{
			return "login_failure";
		}
	}
	
	//这个验证默认对所有方法进行验证，如果需要忽略某个方法的验证
	//可以在那个方法上面添加@SkipValidation 注解。如 logout方法
	@Override
	public void validate() {
		// TODO Auto-generated method stub
		//用户名不能为空
		if ("".equals(user.getUsername().trim())) {
			this.addFieldError("usernameError", "用户名不能为空！");
		}
		if (user.getPassword().length()<6) {
			this.addFieldError("passwordError", "密码长度不少于6位");
		}
	}


	//用户注销方法
	@SkipValidation
	public String logout()
	{
		if (session.getAttribute("loginUserName")!=null) {
			session.removeAttribute("loginUserName");
		}
		return "logout_success";
	}
	
	@Override
	public Users getModel() {
		return this.user;
	}
}
